layui.define(['element', 'form', 'ksUtil', 'layerPlus', 'laytpl', 'load'], function(exports) {
  var $ = layui.jquery
    , form = layui.form
    , laytpl = layui.laytpl
    , element = layui.element
    , utils = layui.ksUtil
    , layer = layui.layerPlus
    , load = layui.load;

  // 初始化富文本
  form.initTextarea = function(model) {
    var $textarea = $('textarea');
    if($textarea) {
      if($('.ok-tinymce').length > 0) {
        load('tinymce', function() {
          var tinymce = layui.tinymce;
          tinymce.render({
            selector: '.ok-tinymce',
            images_upload_url: path + 'file',
            model: model,
            file_base_path: path+'static/upload/',
            height: '400px',
            convert_urls: false
          });
        });
      }
    }
  };

  // 初始化时间控件
  form.initDate = function() {
    var $dateList = $('.ok-date');
    if($dateList && $dateList.length > 0) {
      load('laydate', function() {
        var laydate = layui.laydate;
        layui.each($dateList, function(index, item) {
          var options = $(item).data();
          if(!options.elem) {
            options.elem = '#' + $(item).attr('id');
          }
          options.tigger = 'click';
          laydate.render(options);
        });
      })
    }
  };

  // 初始化动态下拉框
  form.initSelect = function(filter, options) {
    var $select = $(".dynamicSel");
    if($select && $select.length > 0) {
      layui.each($select, function(index, item) {
        var $sel = $(item)
          , url = $sel.attr('data-dynamic-url')
          , selCode = $sel.attr('data-code')
          , valueField = $sel.attr('data-value-field') || 'id'
          , textField = $sel.attr('data-text-field') || 'name';
        utils.get(path + url, {}, options)
          .done(function(result) {
            var rows = result.data || result.rows;
            if(selCode) {
              layui.data('selectData', {
                key: selCode,
                value: rows
              });
            }
            $sel.empty();
            $sel.append('<option value="" selected>-=请选择=-</option>');
            for(var i in rows) {
              var row = rows[i];
              $sel.append('<option value="' + row[valueField] + '" ' + (row.isDefault ? 'selected' : '') + '>' + row[textField] + '</option>');
            }
            form.render('select', filter);
          });
      });
    }
  };

  // 初始化动态表单
  form.initDynamicElements = function(elem, lines, type) {
    $(elem).append('<input type="hidden" name="id"/>');
    layui.each(lines, function(index, line) {
      let html = [
        '<div class="layui-form-item">',
        '   <label class="layui-form-label">' + line.label + '</label>',
        '   <div class="layui-input-block">'
      ];
      if(line.type === 'input') {
        let input = '<input type="text" class="layui-input" name="' + line.name + '" ';
        if(line.placeholder) input += 'placeholder="' + line.placeholder + '" ';
        if(line.verify) input += ' lay-verify="' + line.verify + '" ';
        if(line.otherHtml) input += line.otherHtml;
        input += ' autocomplete="off"/>';
        html.push(input);
      } else if(line.type === 'textarea') {
        let textarea = '<textarea class="layui-textarea" name="' + line.name + '" ';
        if(line.placeholder) textarea += 'placeholder="' + line.placeholder + '" ';
        if(line.verify) textarea += ' lay-verify="' + line.verify + '" ';
        if(line.otherHtml) textarea += line.otherHtml;
        textarea += '></textarea>';
        html.push(textarea)
      } else if(line.type === 'select') {
        let select = '<select name="' + line.name + '" ';
        if(line.verify) select += ' lay-verify="' + line.verify + '" ';
        if(line.otherHtml) select += line.otherHtml;
        select += '>';
        let options = line.options;
        for(let i in options) {
          let data = options[i];
          select += '<option value="' + data.id + '" ';
          if(data.selected) select += 'selected="true" ';
          select += '>' + data.value + '</option>';
        }
        select += '</select>';
        html.push(select);
      } else if(line.type === 'other') {
        html.push(line.html)
      }
      html.push(
        '   </div>',
        '</div>');
      $("form.ok-form").append(html.join(''))
    });
    // if(type !== 'view' && type !== ''){
    //   $("form.ok-form").append([
    //     '<div class="layui-form-item" id="btnDiv">',
    //     '   <div class="layui-input-block">',
    //     '       <button class="layui-btn" lay-submit lay-filter="ok-form">提交</button>',
    //     '       <button type="reset" class="layui-btn layui-btn-primary">重置</button>',
    //     '   </div>',
    //     '</div>'
    //   ].join(''));
    // }
    form.render(); //更新全部
  };

  // 初始化表单事件
  form.initEvents = function(_config) {
    let events = _config.events;

    layui.each(events, function(index, obj) {
      form.on(obj.type + '(' + obj.filter + ')', obj.event)
    })
  };

  // 初始化表单
  form.initForm = function(_config, id) {
    if(_config.value) {
      if(typeof _config.initMethod === 'function') {
        _config.initMethod(_config.value)
      }
      form.val(_config.form, _config.value);
    } else if(id) {
      var url = _config.action.search || _config.basePath + '/{id}';
      if(url) {
        url = url.replace('{id}', id);
        utils.get(url).done(
          function(res) {
            if(typeof _config.initMethod === "function") {
              _config.initMethod(res.data)
            }
            form.val(_config.form, res.data);
          }
        );
      } else {
        layer.msg.error("没有配置请求路径");
      }
    }
  };

  // 初始化提交事件
  form.initSubmitEvent = function(filter, type, _config) {
    if(typeof _config.submit === 'function') {
      form.on('submit(' + filter + ')', _config.submit);
    } else if(type) {
      form.on('submit(' + filter + ')', function(data) {
        if(_config.model) {
          var postData = data.field
            , success = _config.success ? _config.success : defaultSuccess
            , url = _config.basePath
            , submitType = _config.submitType;
          if(type === 'add' || type === 'copy') {
            if(typeof _config.beforeCreate === 'function')
              postData = _config.beforeCreate(postData);

            if(postData) {
              url = _config.action.create || url;
              if(url) {
                delete postData.id;
                if(submitType === 'json') {
                  utils.post(url, JSON.stringify(postData), {contentType: 'application/json;charset=utf-8'}).done(success);
                } else {
                  utils.post(url, postData).done(success);
                }
              } else {
                layer.msg.warn('未配置创建路径！');
              }
            }
          } else if(type === 'edit') {
            if(typeof _config.beforeUpdate === 'function')
              postData = _config.beforeUpdate(postData);

            if(postData) {
              url = _config.action.update || url;
              if(url) {
                if(submitType === 'json') {
                  utils.put(url, JSON.stringify(postData), {contentType: 'application/json;charset=utf-8'})
                    .done(success);
                } else {
                  utils.put(url, postData)
                    .done(success);
                }
              } else {
                layer.msg.warn('未配置更新路径！');
              }
            }
          }
        }
        return false;
      });
    }
  };

  // 初始化导航
  form.initBreadcrumbs = function(type, breadcrumbs) {
    breadcrumbs.push(type === 'add' ? '添加' : type === 'edit' || type === 'copy' ? '编辑' : type === 'view' ? '查看' : type);
    if(breadcrumbs && breadcrumbs.length > 0){
      var html = [];
      layui.each(breadcrumbs, function(index, item){
        if(index == breadcrumbs.length - 1){
          html.push('<a href="javascript:location.replace(location.href)"><cite>'+item+'</cite></a>');
        }else{
          html.push('<a><cite>'+item+'</cite></a>');
        }
      });
      $("span.layui-breadcrumb")[0].innerHTML = html.join('');
      element.render('breadcrumb');
    }
  };

  function defaultSuccess() {
    layer.alert('操作成功', {icon: 1, title: '提示'}, function(i) {
      layer.close(i);
      window.parent.location.reload();
      var index = parent.layer.getFrameIndex(window.name);
      parent.layer.close(index);
    });
  }

  form.defaultSuccess = defaultSuccess;

  exports('formUtil', form);
});
